package com.system.config;

import java.nio.charset.StandardCharsets;
import java.util.List;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.system.interceptor.LogInterceptor;
import com.system.interceptor.MybatisSqlInterceptor;

@SuppressWarnings("rawtypes")
@Configuration
public class WebConfig implements WebMvcConfigurer {

//	@Bean(name = "sqlSessionFactory")
//	@Primary
//	public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource datasource) throws Exception {
//		MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
//		bean.setDataSource(datasource);
//		// bean.setPlugins(mybatisPlusInterceptor());
//		System.out.println("bean = " + bean.toString());
//		return bean.getObject();
//	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(logInterceptor()).addPathPatterns("/**");
		// 可以具体制定哪些需要拦截，哪些不拦截，其实也可以使用自定义注解更灵活完成
//                .addPathPatterns("/**")
//                .excludePathPatterns("/testxx.html");
	}
	
	@Override
	public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
		// 解决controller返回字符串中文乱码问题
		for (HttpMessageConverter<?> converter : converters) {
			if (converter instanceof StringHttpMessageConverter) {
				((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
			}
		}
	}

	@Bean
	public MybatisSqlInterceptor mybatisSqlInterceptor() {
		return new MybatisSqlInterceptor();
	}

	@Bean
	public LogInterceptor logInterceptor() {
		return new LogInterceptor();
	}

}
